using System.IO;
using System.Diagnostics;

using System.Net.DnsToolkit.Packet;
using System.Net.DnsToolkit.Util;
using System.Net.DnsToolkit.Packet.Records;
using System.Net.DnsToolkit.Serializer.Stream.Extension;
using System.Net.DnsToolkit.Packet.Busy;

namespace System.Net.DnsToolkit.Serializer.Stream.Reader {

    public class RRReader : IRRReader<System.IO.Stream> {

        private readonly IRecordReaderProvider<System.IO.Stream> _recordReaderProvider;
        public RRReader(IRecordReaderProvider<System.IO.Stream> recordReaderProvider) {
            _recordReaderProvider = recordReaderProvider;
        }

        public IRR Read(System.IO.Stream ds) {
            IRR rr;
            Read(false, ds, out rr);
            return rr;
        }

        public bool TryRead(System.IO.Stream ds, out IRR rr) {
            return Read(true, ds, out rr);
        }

        public bool Read(bool tryRead, System.IO.Stream source, out IRR rr) {


            IDomainName domn = source.ReadDomainName();
            ushort rtype = source.Read16();
            ushort rclass = source.Read16();
            uint ttl = source.Read32();
            ushort length = source.Read16();
            QTypeEnum qTypeEnum = Enum<QTypeEnum>.ToObject(rtype);
            QClassEnum qClassEnum = Enum<QClassEnum>.ToObject(rclass);

            var recordReader = _recordReaderProvider.Provide(qTypeEnum);

            IRecord record;
            long position = source.Position;
            recordReader.TryRead(source, out record);
            long position2 = source.Position;
            
            Debug.Assert(position == position2 - length);

            var r = new RR {
                Name= domn,
                RRType = qTypeEnum,
                RRClass = qClassEnum,
                Ttl = ttl,
                RDLength = length,
                RData = record
            };

            rr = r;

            return true;
        }


    }
}